<!--
 * @Descripttion: 
 * @version: 
 * @Author: wl
 * @Date: 2020-06-05 11:09:48
 * @LastEditors: wl
 * @LastEditTime: 2020-07-10 15:02:44
--> 

<template>
  <div style="height: 100%;" class="permission">
    <div class="search_wrap">
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText"
        style="width: calc(100% - 100px); margin-right: 8px"
      >
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type="primary" @click="add">新增</el-button>
    </div>

    <el-tree
      class="filter-tree"
      :data="treeData"
      v-loading="loading"
      :props="treeProps"
      :default-expanded-keys="['1000-1000', '1000-1000-1000', '1000-1000-1000-1011', '1000-1000-1000-1011-1041']"
      :node-key="nodeKey"
      :key="tree_key"
      :filter-node-method="filterNode"
      ref="tree"
      :expand-on-click-node="false"
      :style="{ width: width }"
      :render-content="renderContent"
      draggable
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      @node-drop="handleDrop"
      @node-drag-end="handleDragEnd"
      highlight-current
    ></el-tree>
  </div>
</template>

<script>
export default {
  props: {
    width: {
      type: String,
      default: "200px"
    }
  },
  data() {
    return {
      nodeKey: "GID",
      loading: false,
      /* 筛选文本 */
      filterText: "",
      /* 当前节点Id */
      curTreeId: 0,
      tree_key: "0",
      /* 新增节点Id */
      newChildId: -1,
      /* 数据列表 */
      treeData: [],
      /* 数据列表配置 */
      treeProps: {
        label: "name",
        children: "children"
      },
      PGID: "", //创建新节点的时候的父GID
      /* 行点击事件和按钮点击事件间的逻辑处理 */
      opertion: true,
      oldGID: "",
      newGID: ""
    };
  },

  //PGID 组id，查询传入的组id和该组id的下级组（不填默认登录的 GID）。
  // name 组名称。
  // CODE 权限值。
  // status 状态，1-启用，2-删除。不传默认查询全部状态。
  // limit 每页显示条数。
  // page 当前页。

  methods: {
    /* 查询 */
    handleQuery: function () {
      let params = {
        name: "",
        GID: "",
        PGID: "",
        CODE: "",
        status: "1",
        limit: "",
        page: ""
      };
      this.loading = true;
      this.$api.dept.findDeptTree().then((res) => {
        if (res.code == 0) {
          this.loading = false;
          this.treeData = res.data;
        } else {
          this.$message({
            message: "操作失败, " + res.msg,
            type: "error"
          });
        }
      });
    },
    /* 数据筛选 */
    filterNode(value, data) {
      if (!value) return true;
      return data[this.treeProps.label].indexOf(value) !== -1;
    },
    // 数据展示结构
    renderContent(h, { node, data, store }) {
      let _this = this;
      return h(
        "span",

        {
          domProps: {
            draggable: true
          },
          style: {
            width: "100%"
          },
          on: {
            //鼠标移入
            mouseenter: () => {
              _this.curTreeId = data.GID;
            },
            //鼠标离开
            mouseleave: () => {
              _this.curTreeId = 0;
            },
            click: () => {
              _this.click(data, node, store);
            },
            allowDrop: () => {
              console.log("拖拽");
            }
          }
        },
        [
          h(
            "span",
            {
              //显示名称
            },
            node.label
          ),
          h(
            "span",
            {
              style: {
                display: data.GID === _this.curTreeId ? "" : "none",
                position: "absolute",
                right: "20px"
              }
            },
            [
              //添加
              h(
                "el-button",
                {
                  props: {
                    type: "text"
                  },
                  style: {
                    padding: 0
                    // display: this.hasPerm('system_outside-company_save')
                  },
                  on: {
                    click: () => {
                      this.append(data);
                    }
                  }
                },
                "添加"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text"
                  },
                  style: {
                    padding: 0
                    // display: this.hasPerm('system_outside-company_delete')
                  },
                  on: {
                    click: () => {
                      this.remove(node, data);
                    }
                  }
                },
                "删除"
              )
            ]
          )
        ]
      );
    },
    /* 节点点击 */
    click: function (data, node, base) {
      console.log("ppp", data, node, base);
      this.PGID = data.GID;
      if (this.opertion) {
        // 按钮操作处理函数
        this.$emit("click", data, node, base);
      }
      this.opertion = true;
    },
    /* 节点添加 */
    add() {
      let _this = this;
      _this.opertion = false;

      const newChild = {
        CODES: [],
        name: "新名称",
        PGID: "",
        children: []
      };

      // _this.treeData.push(newChild);
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(newChild.PGID);
      });
      _this.newChildId--;

      this.$emit("add", newChild);
    },
    /* 节点追加 */
    append(data) {
      // console.log("鬼东西",data);
      let _this = this;
      _this.opertion = false;
      const newChild = {
        GID: "",
        CODES: data.CODES,
        name: "新节点",
        PGID: data.GID,
        children: []
      };

      if (!data.children) {
        this.$set(data, "children", []);
      }
      // data.children.push(newChild);
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(newChild.PGID);
      });
      _this.newChildId--;
      this.$emit("add", newChild);
    },
    /* 节点移除 */
    remove(node, data) {
      this.opertion = false;
      if (data.id < 0) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex((d) => d.id === data.id);
        children.splice(index, 1);
      } else {
        this.$emit("delete", data, node);
      }
    },
    // 拖动
    allowDrop(draggingNode, dropNode, type) {
      // console.log("25525", draggingNode, dropNode, type);

      // if (dropNode.data.label === "二级 3-1") {
      //   return type !== "inner";
      // } else {
      return true;
      // }
    },
    allowDrag(draggingNode) {
      if (draggingNode.data.GID) {
        this.oldGID = draggingNode.data.GID;
      } else {
        this.oldGID = "";
        return false;
      }
      return true;

      // return draggingNode.data.label.indexOf("三级 3-2-2") === -1;
    },

    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      if (dropType == "inner") {
        this.newGID = dropNode.data.GID;
      } else {
        this.newGID = dropNode.parent.data.GID;
      }
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let params = {
        rows: {
          GID: this.oldGID,
          newGID: this.newGID
        },
        where: { remove: 1 }
      };
      let paramJson = JSON.stringify(params);
      this.$api.dept.save(paramJson).then((res) => {
        // if (res.code == 0) {
        //   this.$emit("RefreshBtn")
        // }
      });
    }
  },
  mounted() {
    this.handleQuery();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  }
};
</script>

<style>
</style>
